package cn.johnyu.order.service.impl;

import cn.johnyu.commons.dto.AccountDto;
import cn.johnyu.commons.dto.ProductDto;
import cn.johnyu.order.client.AccountClient;
import cn.johnyu.order.client.ProductClient;
import cn.johnyu.order.domain.Order;
import cn.johnyu.order.mapper.OrderMapper;
import cn.johnyu.order.po.OrderPo;
import cn.johnyu.order.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ProductClient productClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Order loadOrder(int id) {
        OrderPo po = orderMapper.loadOrder(id);
        ProductDto product = productClient.loadProduct(po.getPid());
        AccountDto account= accountClient.loadAccount(po.getAid());
        return new Order().setId(id).setAccount(account).setProduct(product).setAmount(po.getAmount());
    }

    @Override
    public List<OrderPo> findAllOrders() {
        return orderMapper.findAllOrders();
    }
    @GlobalTransactional
    @Override
    public OrderPo createOrder(int aid, int pid, int count) {
//        todo:从报价系统查价格
        int price=100;
        int amount=count*price;
        productClient.reduceStock(pid,count);
        accountClient.reduceBalance(aid,amount);
        OrderPo po = new OrderPo().setAid(aid).setPid(pid).setAmount(amount);
        orderMapper.addOrder(po);
        return po;

    }
}
